import QRCode from 'qrcode'
export default {
	data(){
		return {
			switchStatus: 0,
			isFull: false,
			playTimeDom: null,
			playTime: '',
			playPauseSrc:[
				require('../../../assets/images/blue.png'),
				require('../../../assets/images/blue.png'),
			],
			videoDom: null,
			containerId: '',
			processId: '',
			showProcessBar: false,
			isPressProcessBar: false,
			imgId: '',
			timeId: '',
			shareId: '',
			share_qr_id: '',
			openShare: false,
			micId: '',
			openMIC: false,
			aiId: '',
			cloudId: '',
			openCloud: false,
			cutId: '',
			screenId: '',
			switch: false,

			canvas_container_id: '',
			canvas_rect_id: '',
			canvas_text_id: '',
			canvas_id: '',
			canvas_close_id: '',
			canvas: null,
			context: null,
			isPress: false,
			x: 0,
			y: 0,
			pointList: [],
			textPointList: [],
			isFillText: false,
			isFillRect: false,
		}
	},
	watch: {
		isFillText(value){
			this.changeImg('text')
			if (value){
				this.isFillRect = false
				this.changeImg('rect')
			}
		},
		isFillRect(value){
			this.changeImg('rect')
			if (value){
				this.isFillText = false
				this.changeImg('text')
			}
		}
	},
	methods: {
		initToolbar() {
			this.initTemplate()
			this.initEvents()
			this.initSwitch()
			this.initDraw()
		},
		initTemplate() {
			let container = this.createContainer()
			let bar = this.createProcessBar()
			let canvasDom = this.createCanvas()
			this.videoDom.parentNode.appendChild(bar)
			this.videoDom.parentNode.appendChild(container)
			this.videoDom.parentNode.appendChild(canvasDom)
			this.initCanvas()
		},
		initEvents(){
			document.getElementById(this.imgId).addEventListener('click', this.clickImg)
			document.getElementById(this.shareId).addEventListener('click', this.clickShare)
			document.getElementById(this.micId).addEventListener('click', this.clickMIC)
			document.getElementById(this.aiId).addEventListener('click', this.clickAI)
			document.getElementById(this.cloudId).addEventListener('click', this.clickCloud)
			document.getElementById(this.cutId).addEventListener('click', this.clickCut)
			document.getElementById(this.screenId).addEventListener('click', this.clickScreen)
			document.getElementById(this.canvas_rect_id).addEventListener('click', this.drawRect)
			document.getElementById(this.canvas_text_id).addEventListener('click', this.drawText)
			document.getElementById(this.canvas_close_id).addEventListener('click', this.hideCanvas)
			let bar_span = document.getElementById(this.processId + '_control')
			if (bar_span){
				bar_span.parentNode.addEventListener('mousedown',()=>{
					this.isPressProcessBar = true
				})
				bar_span.parentNode.addEventListener('mouseup',()=>{
					this.isPressProcessBar = false
				})
				bar_span.parentNode.addEventListener('mousemove',(e)=>{
					if (this.isPressProcessBar){
						bar_span.parentNode.style.width = (e.screenX - this.videoDom.parentNode.getBoundingClientRect().left) + 'px'
						let video_width = this.videoDom.parentNode.offsetWidth
						this.player.currentTime(((e.screenX - this.videoDom.parentNode.getBoundingClientRect().left)) * this.player.duration() / video_width)
					}
				})
			}
			this.videoDom.parentNode.addEventListener('mouseover', () => {
				let toolDom = document.getElementById(this.containerId)
				toolDom.style.visibility = 'visible'
				document.getElementById(this.processId).style.bottom = toolDom.offsetHeight + 'px'
			})
			this.videoDom.parentNode.addEventListener('mouseleave', () => {
				let toolDom = document.getElementById(this.containerId)
				toolDom.style.visibility = 'hidden'
				document.getElementById(this.processId).style.bottom = 0
			})
		},
		initSwitch(){
			setTimeout(()=>{
				let ai = document.getElementById(this.aiId)
				if (this.switch){
					ai.children[1].style.right = 0
					ai.style.background = '#FF8600'
					ai.children[0].style.paddingLeft = '15%'
				}else {
					let px = ai.children[1].getBoundingClientRect().left - ai.getBoundingClientRect().left
					ai.children[1].style.right = px + 'px'
					ai.style.background = '#B2B2B2'
					ai.children[0].style.paddingLeft = '50%'
				}
			},1000)
		},

		createContainer(){
			//容器
			let container = document.createElement('div')
			container.classList.add('control-list')
			container.id = 'toolbar_' + Math.ceil(Math.random() * 10000)
			this.containerId = container.id
			//左侧控制栏
			let left = document.createElement('div')
			left.classList.add('control-left')
			left = this.createLeftButton(left)
			container.appendChild(left)
			//右侧控制
			let right = document.createElement('div')
			right.classList.add('control-right')
			right = this.createRightButton(right)
			container.appendChild(right)
			return container
		},
		createLeftButton(left){
			//播放暂停按钮
			let changeStatus = this.createPlayPause()
			//播放时间
			let time = document.createElement('div')
			time.classList.add('play-time')
			time.id = 'play_time_' + Math.ceil(Math.random() * 10000)
			this.timeId = time.id
			left.appendChild(changeStatus)
			left.appendChild(time)
			return left
		},
		createRightButton(right){
			//分享
			right.appendChild(this.createShareButton())
			//喊话
			right.appendChild(this.createMICButton())
			//ai
			right.appendChild(this.createAIButton())
			//云台
			right.appendChild(this.createCloudButton())
			//截屏
			right.appendChild(this.createCutButton())
			//全屏
			right.appendChild(this.createScreenButton())
			return right
		},
		createShareButton(){
			let shareDom = document.createElement('div')
			shareDom.classList.add('share-button')
			shareDom.id = 'share_' + Math.ceil(Math.random() * 10000)
			shareDom.innerHTML = '分享'
			this.shareId = shareDom.id
			return shareDom
		},
		createMICButton(){
			let micDom = document.createElement('div')
			micDom.classList.add('mic-button')
			micDom.id = 'mic_' + Math.ceil(Math.random() * 10000)
			micDom.innerHTML = '喊话'
			this.micId = micDom.id
			return micDom
		},
		createAIButton(){
			let aiDom = document.createElement('div')
			aiDom.classList.add('ai-button')
			aiDom.id = 'ai_' + Math.ceil(Math.random() * 10000)
			this.aiId = aiDom.id
			//span
			let spanText = document.createElement('span')
			spanText.classList.add('ai-text')
			spanText.innerText = 'AI'
			let spanSwitch = document.createElement('span')
			spanSwitch.classList.add('ai-switch')
			aiDom.appendChild(spanText)
			aiDom.appendChild(spanSwitch)
			return aiDom
		},
		createCloudButton(){
			let cloud = document.createElement('div')
			cloud.classList.add('cloud-button')
			cloud.id = 'cloud_' + Math.ceil(Math.random() * 10000)
			cloud.innerHTML = '云台'
			this.cloudId = cloud.id
			return cloud
		},
		createCutButton(){
			let cut = document.createElement('div')
			cut.classList.add('cut-button')
			cut.id = 'cut_' + Math.ceil(Math.random() * 10000)
			this.cutId = cut.id
			return cut
		},
		createScreenButton(){
			let screen = document.createElement('div')
			screen.classList.add('screen-button')
			screen.id = 'screen_' + Math.ceil(Math.random() * 10000)
			this.screenId = screen.id
			return screen
		},
		createPlayPause(){
			//播放暂停按钮
			let changeStatus = document.createElement('div')
			changeStatus.classList.add('changeStatus')
			let img = document.createElement('img')
			img.src = this.playPauseSrc[0]
			img.style.width = '1rem'
			img.style.height = '1rem'
			img.id = 'change_status_' + Math.ceil(Math.random() * 10000)
			this.imgId = img.id
			changeStatus.appendChild(img)
			return changeStatus
		},
		createCanvas(){
			let canvasDom = document.createElement('div')
			canvasDom.id = 'canvas__container' + Math.ceil(Math.random() * 10000)

			let canvas_id = 'canvas_' + Math.ceil(Math.random() * 10000)
			let canvas_rect_id = 'canvas_rect_' + Math.ceil(Math.random() * 10000)
			let canvas_text_id = 'canvas_text_' + Math.ceil(Math.random() * 10000)
			let canvas_close_id = 'canvas_close_' + Math.ceil(Math.random() * 10000)
			this.canvas_container_id = canvasDom.id
			this.canvas_id = canvas_id
			this.canvas_rect_id = canvas_rect_id
			this.canvas_text_id = canvas_text_id
			this.canvas_close_id = canvas_close_id

			canvasDom.classList.add('canvas-container')
			canvasDom.innerHTML = `
			<canvas class="canvas" id="${canvas_id}"></canvas>
			<div class="tools">
				<div class="close-canvas" id="${canvas_close_id}"></div>
				<div id="${canvas_rect_id}" class="canvas-rect"><img src="${require('../../../assets/images/blue.png')}" ></div>
				<div id="${canvas_text_id}" class="canvas-text"><img src="${require('../../../assets/images/blue.png')}"></div>
			</div>`
			return canvasDom
		},
		createProcessBar(){
			let bar = document.createElement('div')
			bar.classList.add('process-bar')
			bar.id = 'process_bar_' + Math.ceil(Math.random() * 10000)
			bar.innerHTML = `<div class="played-bar"><span id="${bar.id + '_control'}"></span></div>`
			this.processId = bar.id
			return bar
		},

		clickImg(){
			this.isPlaying = !this.isPlaying
		},
		activeShare(){
			let share = document.getElementById(this.shareId)
			let share_qr = document.getElementById(this.share_qr_id)
			if (!share_qr){
				share_qr = document.createElement('div')
				share_qr.classList.add('share_qr')
				share_qr.id = this.shareId + '_share'
				this.share_qr_id = share_qr.id
			}
			share_qr.style.visibility = 'visible'
			share_qr.style.left = (share.offsetLeft - 70) + 'px'
			share_qr.innerHTML = `<div class="qr-img"><img src="" id="${this.share_qr_id + '_img'}"></div><div class="qr-text">手机微信扫码分享</div>`
			this.videoDom.parentNode.appendChild(share_qr)
			let id = this.share_qr_id + '_img',text = this.share
			QRCode.toDataURL(text, { errorCorrectionLevel: 'M' }, function (err, url) {
				let share_img = document.getElementById(id)
				share_img.src = url
				share_img.title = text
			})
		},
		inActiveShare(){
			let share_qr = document.getElementById(this.shareId + '_share' )
			share_qr.style.visibility = 'hidden'
		},
		clickShare(){
			this.openShare = !this.openShare
			if (this.openShare){
				this.activeShare()
				document.getElementById(this.shareId).classList.add('cus-button-active')
			}else {
				this.inActiveShare()
				document.getElementById(this.shareId).classList.remove('cus-button-active')
			}
			this.$emit('share')
		},
		clickMIC(){
			this.openMIC = !this.openMIC
			if (this.openMIC){
				document.getElementById(this.micId).classList.add('cus-button-active')
			}else {
				document.getElementById(this.micId).classList.remove('cus-button-active')
			}
			this.$emit('mic')
		},
		clickAI(){
			let ai = document.getElementById(this.aiId)
			this.switch = !this.switch
			if (this.switch){
				ai.children[1].style.right = 0
				ai.style.background = '#FF8600'
				ai.children[0].style.paddingLeft = '15%'
			}else {
				let px = ai.children[1].getBoundingClientRect().left - ai.getBoundingClientRect().left
				ai.children[1].style.right = px + 'px'
				ai.style.background = '#B2B2B2'
				ai.children[0].style.paddingLeft = '50%'
			}
			this.$emit('ai')
		},
		clickCloud(){
			this.openCloud = !this.openCloud
			if (this.openCloud){
				document.getElementById(this.cloudId).classList.add('cus-button-active')
			}else {
				document.getElementById(this.cloudId).classList.remove('cus-button-active')
			}
			this.$emit('cloud')
		},
		clickCut(){
			this.showCanvasContainer()
			this.isPlaying = false
			this.$emit('cut')
		},
		clickScreen(){
      this.$emit('childByValue', 'fullScreen')
			if (this.isFull){
				this.player.exitFullscreen()
			}else {
				this.player.requestFullscreen()
			}
			this.isFull = !this.isFull
			this.initCanvas()
			this.$emit('screen')
		},


		hideCanvas(){
			this.showCanvasContainer('hidden')
		},
		initCanvas(){
			let dom = document.getElementById(this.canvas_container_id)
			this.canvas = document.getElementById(this.canvas_id)
			this.canvas.width = dom.offsetWidth * 0.8
			this.canvas.height = dom.offsetHeight * 0.8
			this.canvas.style.background = 'red'

			this.context = this.canvas.getContext('2d')

			window.addEventListener('resize', () => {
				this.canvas.width = dom.offsetWidth *0.8
				this.canvas.height = dom.offsetHeight * 0.8
				this.drawAgo()
			})
		},
		showCanvasContainer(visible = 'visible'){
			if (visible === 'visible') {
				//初始化画板数据
				this.initCanvasData()
				this.initProto()
				this.drawVideo()
			}
			document.getElementById(this.canvas_container_id).style.visibility = visible
		},
		//canvas操作
		drawVideo(){
			this.context.drawImage(this.videoDom, 0, 0, this.canvas.width, this.canvas.height)
		},
		drawRect(){
			this.isFillRect = !this.isFillRect
		},
		drawText(){
			this.isFillText = !this.isFillText
		},
		changeImg(type){
			if (type === 'rect'){
				let rect = document.getElementById(this.canvas_rect_id)
				if (this.isFillRect){
					rect.children[0].src = require('../../../assets/images/blue.png')
				}else {
					rect.children[0].src = require('../../../assets/images/blue.png')
				}
			}
			if (type === 'text'){
				let text = document.getElementById(this.canvas_text_id)
				if (this.isFillText){
					text.children[0].src = require('../../../assets/images/blue.png')
				}else {
					text.children[0].src = require('../../../assets/images/blue.png')
				}
			}
		},
		initCanvasData(){
			this.isPress = false
			this.x = 0
			this.y = 0
			this.pointList = []
			this.textPointList = []
			this.isFillText = false
			this.isFillRect = false
		},
		initDraw(){
			this.canvas.addEventListener('mousedown', (e) => {
				let box = this.canvas.getBoundingClientRect()
				this.isPress = true
				this.x = e.clientX - box.left
				this.y = e.clientY - box.top
				if (this.isPress && this.isFillText) {
					this.textPointList.push([e.layerX,e.layerY])
					let input = document.getElementById('fill_text')
					if (!input) {
						//创建dom
						input = document.createElement('input');
						input.style.position = 'absolute'
						input.style.zIndex = 9999
						input.style.width = '150px'
						input.style.height = '30px'
						input.id = 'fill_text'
						document.getElementById(this.canvas_container_id).append(input)
					}else {
						input.style.display = 'block'
					}
					input.style.top = e.layerY + 'px'
					input.style.left = e.layerX + 'px'
					input.addEventListener('blur', () => {
						let [x,y] = this.textPointList[this.textPointList.length -1]
						this.textPointList[this.textPointList.length -1].push(input.value)
						this.context.wrapText(input.value, x, y, 150);
						input.style.display = 'none'
					})
					this.isFillText = false
				}
			})
			this.canvas.addEventListener('mouseup', (e) => {
				let box = this.canvas.getBoundingClientRect()
				this.isPress = false
				let x = e.clientX - box.left
				let y = e.clientY - box.top
				this.pointList.push([this.x, this.y, x - this.x, y - this.y])
			})
			this.canvas.addEventListener('mousemove', (e) => {
				let box = this.canvas.getBoundingClientRect()
				if (this.isPress && this.isFillRect) {
					let x = e.clientX - box.left
					let y = e.clientY - box.top
					this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
					this.context.moveTo(this.x, this.y)
					this.context.beginPath()
					this.context.strokeStyle = 'red'
					this.context.lineWidth = 3
					this.drawAgo()
					//绘制新的
					this.context.strokeRect(this.x, this.y, x - this.x, y - this.y);
				}
			})
		},
		drawAgo(){
			this.drawVideo()
			this.context.moveTo(this.x, this.y)
			this.context.beginPath()
			//绘制之前的
			this.pointList.map(point => {
				this.context.strokeRect(point[0], point[1], point[2], point[3]);
			})
			this.textPointList.map(text => {
				this.context.wrapText(text[2], text[0], text[1], 150);
			})
		},
		initProto(){
			CanvasRenderingContext2D.prototype.wrapText = function(text, x, y, maxWidth, lineHeight = 15) {
				let lines = text.split("\n");
				this.font = '16px STheiti, SimHei';
				this.fillStyle = 'red'
				for (let i = 0; i < lines.length; i++) {
					let words = lines[i].split(' ');
					let line = '';
					for (let n = 0; n < words.length; n++) {
						let testLine = line + words[n] + ' ';
						let metrics = this.measureText(testLine);
						let testWidth = metrics.width;
						if (testWidth > maxWidth && n > 0) {
							this.fillText(line, x, y);
							line = words[n] + ' ';
							y += lineHeight;
						} else {
							line = testLine;
						}
					}
					this.fillText(line, x, y);
					y += lineHeight;
				}
			}
		}
	}
}
